/**
 * 基于局域网的视频网站系统 - 通用JavaScript工具库
 */

// 全局配置
const CONFIG = {
    API_BASE_URL: '/api',
    UPLOAD_MAX_SIZE: 500 * 1024 * 1024, // 500MB
    SUPPORTED_VIDEO_TYPES: ['video/mp4', 'video/avi', 'video/mkv', 'video/webm'],
    SESSION_TIMEOUT: 30 * 60 * 1000, // 30分钟
};

// 工具函数
const Utils = {
    // 格式化时间
    formatTime: function(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN');
    },

    // 格式化文件大小
    formatFileSize: function(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    // 格式化时长
    formatDuration: function(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = Math.floor(seconds % 60);
        
        if (hours > 0) {
            return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        } else {
            return `${minutes}:${secs.toString().padStart(2, '0')}`;
        }
    },

    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    // 生成唯一ID
    generateId: function() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

    // 验证邮箱
    validateEmail: function(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    },

    // 验证用户名
    validateUsername: function(username) {
        return /^[a-zA-Z0-9_]{3,20}$/.test(username);
    },

    // 验证密码
    validatePassword: function(password) {
        return password.length >= 6;
    },

    // 获取URL参数
    getUrlParam: function(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    },

    // 设置URL参数
    setUrlParam: function(name, value) {
        const url = new URL(window.location);
        url.searchParams.set(name, value);
        window.history.replaceState({}, '', url);
    },

    // 复制到剪贴板
    copyToClipboard: function(text) {
        if (navigator.clipboard) {
            return navigator.clipboard.writeText(text);
        } else {
            // 兼容旧浏览器
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand('copy');
                return Promise.resolve();
            } catch (err) {
                return Promise.reject(err);
            } finally {
                document.body.removeChild(textArea);
            }
        }
    }
};

// API请求封装
const API = {
    // 基础请求方法
    request: async function(url, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'same-origin', // 包含cookies
        };

        const finalOptions = { ...defaultOptions, ...options };

        try {
            const response = await fetch(url, finalOptions);
            
            // 检查是否是认证失败
            if (response.status === 401 || response.status === 403) {
                Message.error('登录已过期，请重新登录');
                UserManager.clearLocalUser();
                setTimeout(() => {
                    window.location.href = '/login.html';
                }, 1500);
                throw new Error('认证失败');
            }
            
            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.message || '请求失败');
            }
            
            return data;
        } catch (error) {
            console.error('API请求错误:', error);
            throw error;
        }
    },

    // GET请求
    get: function(endpoint) {
        return this.request(`${CONFIG.API_BASE_URL}${endpoint}`, {
            method: 'GET',
        });
    },

    // POST请求
    post: function(endpoint, data) {
        return this.request(`${CONFIG.API_BASE_URL}${endpoint}`, {
            method: 'POST',
            body: JSON.stringify(data),
        });
    },

    // PUT请求
    put: function(endpoint, data) {
        return this.request(`${CONFIG.API_BASE_URL}${endpoint}`, {
            method: 'PUT',
            body: JSON.stringify(data),
        });
    },

    // DELETE请求
    delete: function(endpoint) {
        return this.request(`${CONFIG.API_BASE_URL}${endpoint}`, {
            method: 'DELETE',
        });
    },

    // 文件上传
    upload: function(endpoint, formData) {
        return this.request(`${CONFIG.API_BASE_URL}${endpoint}`, {
            method: 'POST',
            body: formData,
            headers: {}, // 不设置Content-Type，让浏览器自动设置
        });
    }
};

// 用户管理
const UserManager = {
    // 当前用户信息缓存
    _currentUser: null,
    _isInitialized: false,

    // 初始化用户信息
    init: async function() {
        if (this._isInitialized) return this._currentUser;
        
        try {
            // 先从本地存储获取
            const localUser = this.getLocalUser();
            if (localUser) {
                this._currentUser = localUser;
                this._isInitialized = true;
                return this._currentUser;
            }
            
            // 如果本地没有，从服务器获取
            const response = await API.get('/user/current');
            if (response.success && response.user) {
                this._currentUser = response.user;
                this.saveLocalUser(response.user);
                this._isInitialized = true;
                return this._currentUser;
            }
            
            this._currentUser = null;
            this._isInitialized = true;
            return null;
        } catch (error) {
            console.error('初始化用户信息失败:', error);
            this._currentUser = null;
            this._isInitialized = true;
            return null;
        }
    },

    // 获取当前用户信息（同步方法）
    getCurrentUser: function() {
        if (!this._isInitialized) {
            // 如果未初始化，尝试从本地存储获取
            return this.getLocalUser();
        }
        return this._currentUser;
    },

    // 获取当前用户信息（异步方法）
    getCurrentUserAsync: async function() {
        return await this.init();
    },

    // 从本地存储获取用户信息
    getLocalUser: function() {
        try {
            const userData = sessionStorage.getItem('user');
            if (userData) {
                return JSON.parse(userData);
            }
        } catch (error) {
            console.error('解析本地用户信息失败:', error);
        }
        return null;
    },

    // 保存用户信息到本地存储
    saveLocalUser: function(user) {
        try {
            sessionStorage.setItem('user', JSON.stringify(user));
            localStorage.setItem('user', JSON.stringify(user));
        } catch (error) {
            console.error('保存用户信息失败:', error);
        }
    },

    // 清除本地用户信息
    clearLocalUser: function() {
        sessionStorage.removeItem('user');
        localStorage.removeItem('user');
        this._currentUser = null;
        this._isInitialized = false;
    },

    // 设置当前用户
    setCurrentUser: function(user) {
        this._currentUser = user;
        this._isInitialized = true;
        this.saveLocalUser(user);
    },

    // 检查用户权限
    hasPermission: function(requiredRole) {
        const userRole = this.getUserRole();
        if (userRole === null) return false;
        
        // 管理员拥有所有权限
        if (userRole === 0) return true;
        
        return userRole === requiredRole;
    },

    // 获取用户角色
    getUserRole: function() {
        const user = this.getCurrentUser();
        return user ? user.role : null;
    },

    // 获取用户ID
    getUserId: function() {
        const user = this.getCurrentUser();
        return user ? user.id : null;
    },

    // 获取用户名
    getUserName: function() {
        const user = this.getCurrentUser();
        return user ? (user.name || user.username) : null;
    },

    // 获取角色名称
    getRoleName: function(role) {
        const roleNames = ['管理员', '老师', '学生'];
        return roleNames[role] || '未知';
    },

    // 检查是否已登录
    isLoggedIn: function() {
        return this.getUserRole() !== null;
    },

    // 重定向到登录页
    redirectToLogin: function() {
        window.location.href = '/login.html';
    },

    // 检查登录状态并重定向
    checkAuth: function() {
        if (!this.isLoggedIn()) {
            this.redirectToLogin();
            return false;
        }
        return true;
    },

    // 统一退出登录函数
    logout: async function() {
        try {
            const response = await API.post('/user/logout');
            if (response.success) {
                // 清除本地存储
                this.clearLocalUser();
                
                // 显示成功消息
                Message.success('退出登录成功');
                
                // 跳转到登录页面
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1000);
            } else {
                Message.error(response.message || '退出登录失败');
            }
        } catch (error) {
            console.error('退出登录失败:', error);
            Message.error('退出登录失败：' + error.message);
            
            // 即使API调用失败，也清除本地存储并跳转
            this.clearLocalUser();
            setTimeout(() => {
                window.location.href = '../login.html';
            }, 2000);
        }
    }
};

// 消息提示系统
const Message = {
    // 显示成功消息
    success: function(message, duration = 3000) {
        this.show(message, 'success', duration);
    },

    // 显示错误消息
    error: function(message, duration = 5000) {
        this.show(message, 'error', duration);
    },

    // 显示警告消息
    warning: function(message, duration = 4000) {
        this.show(message, 'warning', duration);
    },

    // 显示信息消息
    info: function(message, duration = 3000) {
        this.show(message, 'info', duration);
    },

    // 显示消息
    show: function(message, type = 'info', duration = 3000) {
        // 创建消息容器
        let container = document.getElementById('message-container');
        if (!container) {
            container = document.createElement('div');
            container.id = 'message-container';
            container.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                max-width: 400px;
            `;
            document.body.appendChild(container);
        }

        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `alert alert-${type === 'error' ? 'danger' : type}`;
        messageEl.style.cssText = `
            margin-bottom: 10px;
            animation: slideIn 0.3s ease;
            position: relative;
        `;
        messageEl.innerHTML = `
            ${message}
            <button type="button" class="btn-close" onclick="this.parentElement.remove()" style="
                position: absolute;
                top: 5px;
                right: 10px;
                background: none;
                border: none;
                font-size: 18px;
                cursor: pointer;
                color: inherit;
            ">&times;</button>
        `;

        container.appendChild(messageEl);

        // 自动移除
        if (duration > 0) {
            setTimeout(() => {
                if (messageEl.parentElement) {
                    messageEl.remove();
                }
            }, duration);
        }
    }
};

// 模态框管理
const Modal = {
    // 显示模态框
    show: function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('show');
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    },

    // 隐藏模态框
    hide: function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('show');
            modal.style.display = 'none';
            document.body.style.overflow = '';
        }
    },

    // 创建确认对话框
    confirm: function(message, callback) {
        const modalId = 'confirm-modal';
        let modal = document.getElementById(modalId);
        
        if (!modal) {
            modal = document.createElement('div');
            modal.id = modalId;
            modal.className = 'modal';
            modal.innerHTML = `
                <div class="modal-dialog">
                    <div class="modal-header">
                        <h5 class="modal-title">确认</h5>
                        <button type="button" class="modal-close" onclick="Modal.hide('${modalId}')">&times;</button>
                    </div>
                    <div class="modal-body">
                        <p id="confirm-message">${message}</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" onclick="Modal.hide('${modalId}')">取消</button>
                        <button type="button" class="btn btn-danger" id="confirm-btn">确认</button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }

        document.getElementById('confirm-message').textContent = message;
        
        // 移除之前的事件监听器
        const confirmBtn = document.getElementById('confirm-btn');
        const newConfirmBtn = confirmBtn.cloneNode(true);
        confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
        
        // 添加新的事件监听器
        newConfirmBtn.addEventListener('click', () => {
            this.hide(modalId);
            if (callback) callback();
        });

        this.show(modalId);
    }
};

// 加载状态管理
const Loading = {
    // 显示加载状态
    show: function(element) {
        if (typeof element === 'string') {
            element = document.getElementById(element);
        }
        
        if (element) {
            element.innerHTML = '<div class="loading"></div> 加载中...';
            element.style.textAlign = 'center';
            element.style.padding = '20px';
        }
    },

    // 隐藏加载状态
    hide: function(element) {
        if (typeof element === 'string') {
            element = document.getElementById(element);
        }
        
        if (element) {
            element.innerHTML = '';
            element.style.textAlign = '';
            element.style.padding = '';
        }
    }
};

// 表单验证
const FormValidator = {
    // 验证表单
    validate: function(form) {
        const errors = [];
        const inputs = form.querySelectorAll('input, select, textarea');
        
        inputs.forEach(input => {
            const value = input.value.trim();
            const required = input.hasAttribute('required');
            const type = input.type;
            const name = input.name;
            
            // 必填验证
            if (required && !value) {
                errors.push(`${this.getFieldLabel(input)}不能为空`);
                input.classList.add('is-invalid');
            } else {
                input.classList.remove('is-invalid');
            }
            
            // 类型验证
            if (value) {
                switch (type) {
                    case 'email':
                        if (!Utils.validateEmail(value)) {
                            errors.push(`${this.getFieldLabel(input)}格式不正确`);
                            input.classList.add('is-invalid');
                        }
                        break;
                    case 'password':
                        if (!Utils.validatePassword(value)) {
                            errors.push(`${this.getFieldLabel(input)}至少6位`);
                            input.classList.add('is-invalid');
                        }
                        break;
                }
                
                // 用户名验证
                if (name === 'username' && !Utils.validateUsername(value)) {
                    errors.push('用户名只能包含字母、数字、下划线，长度3-20位');
                    input.classList.add('is-invalid');
                }
            }
        });
        
        return {
            isValid: errors.length === 0,
            errors: errors
        };
    },

    // 获取字段标签
    getFieldLabel: function(input) {
        const label = input.closest('.form-group')?.querySelector('.form-label');
        return label ? label.textContent : input.name;
    },

    // 清除验证状态
    clearValidation: function(form) {
        const inputs = form.querySelectorAll('.is-invalid');
        inputs.forEach(input => input.classList.remove('is-invalid'));
    }
};

// 文件上传管理
const FileUpload = {
    // 验证文件
    validateFile: function(file) {
        const errors = [];
        
        // 检查文件大小
        if (file.size > CONFIG.UPLOAD_MAX_SIZE) {
            errors.push(`文件大小不能超过${Utils.formatFileSize(CONFIG.UPLOAD_MAX_SIZE)}`);
        }
        
        // 检查文件类型
        if (!CONFIG.SUPPORTED_VIDEO_TYPES.includes(file.type)) {
            errors.push('只支持MP4、AVI、MKV、WebM格式的视频文件');
        }
        
        return {
            isValid: errors.length === 0,
            errors: errors
        };
    },

    // 上传文件
    upload: async function(file, endpoint, onProgress) {
        const validation = this.validateFile(file);
        if (!validation.isValid) {
            throw new Error(validation.errors.join(', '));
        }
        
        const formData = new FormData();
        formData.append('file', file);
        
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            
            // 上传进度
            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable && onProgress) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    onProgress(percentComplete);
                }
            });
            
            // 上传完成
            xhr.addEventListener('load', () => {
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        resolve(response);
                    } catch (error) {
                        reject(new Error('响应格式错误'));
                    }
                } else {
                    reject(new Error(`上传失败: ${xhr.status}`));
                }
            });
            
            // 上传错误
            xhr.addEventListener('error', () => {
                reject(new Error('网络错误'));
            });
            
            xhr.open('POST', `${CONFIG.API_BASE_URL}${endpoint}`);
            xhr.send(formData);
        });
    }
};

// 视频播放器管理
const VideoPlayer = {
    // 创建播放器
    create: function(containerId, videoSrc, options = {}) {
        const container = document.getElementById(containerId);
        if (!container) return null;
        
        const player = document.createElement('video');
        player.src = videoSrc;
        player.controls = true;
        player.preload = 'metadata';
        
        // 设置样式
        player.style.width = '100%';
        player.style.height = 'auto';
        player.style.borderRadius = '8px';
        
        // 设置选项
        if (options.autoplay) player.autoplay = true;
        if (options.muted) player.muted = true;
        if (options.loop) player.loop = true;
        
        container.innerHTML = '';
        container.appendChild(player);
        
        return player;
    },

    // 获取播放进度
    getProgress: function(player) {
        if (!player || !player.duration) return 0;
        return (player.currentTime / player.duration) * 100;
    },

    // 设置播放进度
    setProgress: function(player, percent) {
        if (!player || !player.duration) return;
        player.currentTime = (percent / 100) * player.duration;
    }
};

// 页面初始化
document.addEventListener('DOMContentLoaded', async function() {
    // 初始化用户信息
    await UserManager.init();
    
    // 初始化侧边栏切换
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('show');
        });
    }
    
    // 初始化模态框关闭
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal')) {
            e.target.style.display = 'none';
            document.body.style.overflow = '';
        }
    });
    
    // 初始化表单验证
    const forms = document.querySelectorAll('form[data-validate]');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const validation = FormValidator.validate(form);
            if (!validation.isValid) {
                e.preventDefault();
                Message.error(validation.errors.join('<br>'));
            }
        });
    });
    
    // 检查用户登录状态（首页、登录和注册页面允许未登录访问）
    const currentPath = window.location.pathname;
    const isLoginPage = currentPath.includes('login.html');
    const isRegisterPage = currentPath.includes('register.html');
    const isIndexPage = currentPath === '/' || currentPath === '/index.html';
    
    // 除了首页、登录和注册页面，其他页面都需要登录
    if (!isLoginPage && !isRegisterPage && !isIndexPage) {
        if (!UserManager.isLoggedIn()) {
            Message.error('请先登录才能访问此页面');
            setTimeout(() => {
                window.location.href = '/login.html';
            }, 1500);
            return;
        }
    }
    
    // 初始化用户信息显示
    updateUserInfoDisplay();
    
    // 初始化退出登录按钮
    const logoutButtons = document.querySelectorAll('[data-logout]');
    logoutButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            UserManager.logout();
        });
    });
});

// 更新用户信息显示
function updateUserInfoDisplay() {
    const user = UserManager.getCurrentUser();
    
    if (user) {
        // 更新用户名显示
        const userNameElements = document.querySelectorAll('[data-user-name]');
        userNameElements.forEach(el => {
            el.textContent = user.name || user.username;
        });
        
        // 更新用户角色显示
        const userRoleElements = document.querySelectorAll('[data-user-role]');
        userRoleElements.forEach(el => {
            el.textContent = UserManager.getRoleName(user.role);
        });
        
        // 更新用户ID显示
        const userIdElements = document.querySelectorAll('[data-user-id]');
        userIdElements.forEach(el => {
            el.textContent = user.id;
        });
        
        // 根据用户角色显示/隐藏特定元素
        const adminElements = document.querySelectorAll('[data-role="admin"]');
        const teacherElements = document.querySelectorAll('[data-role="teacher"]');
        const studentElements = document.querySelectorAll('[data-role="student"]');
        
        adminElements.forEach(el => {
            el.style.display = user.role === 0 ? '' : 'none';
        });
        
        teacherElements.forEach(el => {
            el.style.display = user.role === 1 ? '' : 'none';
        });
        
        studentElements.forEach(el => {
            el.style.display = user.role === 2 ? '' : 'none';
        });
        
        // 显示登录状态
        const loginStatusElements = document.querySelectorAll('[data-login-status]');
        loginStatusElements.forEach(el => {
            el.textContent = '已登录';
            el.className = 'text-success';
        });
        
        // 隐藏登录按钮，显示用户信息
        const loginButtons = document.querySelectorAll('[data-login-button]');
        const userInfoButtons = document.querySelectorAll('[data-user-info]');
        
        loginButtons.forEach(el => el.style.display = 'none');
        userInfoButtons.forEach(el => el.style.display = '');
        
    } else {
        // 未登录状态
        const loginStatusElements = document.querySelectorAll('[data-login-status]');
        loginStatusElements.forEach(el => {
            el.textContent = '未登录';
            el.className = 'text-danger';
        });
        
        // 显示登录按钮，隐藏用户信息
        const loginButtons = document.querySelectorAll('[data-login-button]');
        const userInfoButtons = document.querySelectorAll('[data-user-info]');
        
        loginButtons.forEach(el => el.style.display = '');
        userInfoButtons.forEach(el => el.style.display = 'none');
        
        // 隐藏角色相关元素
        const roleElements = document.querySelectorAll('[data-role]');
        roleElements.forEach(el => {
            el.style.display = 'none';
        });
    }
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
`;
document.head.appendChild(style);
